<?php
declare(strict_types=1);

namespace App\Logic\User\Service\Image;

use App\Constant\CacheKey;
use App\Library\HttpClient;
use App\Library\RedisClient;
use App\Logic\User\Repository\Image\ImageItemRepository;
use App\Logic\User\Service\User\UserScoreHistoryService;
use App\Logic\User\Service\UserServiceInterface;
use Closure;
use Illuminate\Support\Facades\Storage;

class ImageItemService implements UserServiceInterface
{
    public static function searchWhere(array $requestParams): Closure
    {
        return function ($query) use ($requestParams) {
            extract($requestParams);
            $query->where("is_show", "=", 1);
            if (!empty($image_uid)) {
                $query->where("image_uid", "=", $image_uid);
            }
            if (!empty($image_item_uid)) {
                $query->where("uid", "=", $image_item_uid);
            }
        };
    }

    public function serviceSelect(array $requestParams): array
    {
        return (new ImageItemRepository())->repositorySelect(self::searchWhere($requestParams), (int)($requestParams["size"] ?? 20),
            ["url", "path", "author_uid", "user_uid", "created_at as upload_time", "uid"]);
    }

    public function serviceCreate(array $requestParams): array
    {
        return [];
    }

    public function serviceUpdate(array $requestParams): array
    {
        return [];
    }

    public function serviceDelete(array $requestParams): int
    {
        return 0;
    }

    public function serviceFind(array $requestParams): array
    {
        if (isset($requestParams["image_uid"])) {
            $imageItems = new ImageItemRepository();
            $image = $imageItems->repositoryFind(self::searchWhere([
                "image_item_uid" => $requestParams["image_uid"]
            ]), ["url", "path", "image_uid", "author_uid"]);
            if (count($image) > 0) {
                $downloadFile = Storage::disk("public_disk")->put($image["path"], (new HttpClient())::client()->get($image["url"] . $image["path"], ['verify' => false])->getBody());
                if ($downloadFile) {
                    $createResult = (new UserScoreHistoryService())->serviceCreate([
                        "score" => 5,
                        "type" => 2,
                        "title" => "壁纸下载",
                    ]);
                    if ($createResult["code"] == 1) {
                        RedisClient::client()->decrBy(CacheKey::$scoreKey . $createResult["user_uid"], 5);
                        $imageItems->incrByDownload((int)$image["image_uid"], (int)$requestParams["image_uid"], (int)$image["author_uid"], (int)$createResult["user_uid"]);
                        return [
                            "code" => 1,
                            "msg" => "请求成功",
                            "url" => config("app.url") . $image["path"],
                            "template_id" => "rF4db7Etb86eqK7iD0FF8MEhLL6z9Vi7sjukCPOhPHQ", // 后端返回，避免修改模板，每次都要重新发布一次微信小程序
                        ];
                    }
                }
            }
        }
        return [
            "code" => 2,
            "url" => "",
            "msg" => "图片暂无法下载",
            "template_id" => "rF4db7Etb86eqK7iD0FF8MEhLL6z9Vi7sjukCPOhPHQ"
        ];
    }
}
